package com.jinlele.service.services;

import java.util.Date;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.jinlele.dao.TradeRecordMapper;
import com.jinlele.model.TradeRecord;
import com.jinlele.model.pay.TradeReq;
import com.jinlele.service.interfaces.IPayService;
import com.jinlele.util.StringHelper;

@Service
public class PayServiceImpl implements IPayService {

	@Resource
	TradeRecordMapper tradeRecordMapper;
	
	@Override
	public boolean checkRepeatOrder(TradeReq req) {
		// 判断订单号是否重复
		TradeRecord selRecord = new TradeRecord();
		selRecord.setOrderNo(req.getOrderNo());
		selRecord.setSysCode(req.getSysCode());
		TradeRecord oldRecord = tradeRecordMapper.findSingleByProperty(selRecord);
		if (oldRecord != null
				&& ("OK".equals(oldRecord.getTradeStatus()) || "QOK"
						.equals(oldRecord.getTradeStatus())))
			return true;
		
		return false;
	}

	@Override
	public TradeRecord createTradeRecord(TradeReq req) {
		
		//判断重复订单
		if(checkRepeatOrder(req)){
			throw new RuntimeException("订单已经支付成功，重复提交!");
		}
				
		// 记录日志
		TradeRecord rec = new TradeRecord();
		rec.setTradeId("D".concat(StringHelper.getOrderNum()));
		rec.setSysCode(req.getSysCode());
		rec.setPayType(req.getPayType());
		rec.setUserNo(req.getUserNo());
		rec.setUserDesc(req.getUserDesc());
		rec.setOrderNo(req.getOrderNo());
		rec.setOrderDesc(req.getOrderDesc());
		rec.setOrderAmount(req.getOrderAmount());
		rec.setTradeTime(new Date());
		rec.setNotifyUrl(req.getNotifyUrl());
		tradeRecordMapper.insert(rec);
		return rec;
	}

}
